import React, { Component } from 'react';
import { Input, InputNumber } from 'antd';
import 'styles/financial-management/expense-view/number-range.scss';

const InputGroup = Input.Group;

class NumberRange extends Component {
  constructor(props) {
    super(props);
    this.state = {
      elementProps: [
        {
          onChange: this.handleStartNumber,
          className: 'number-range-group__input',
          key: 'startNumber',

        },
        {
          className: 'number-range-group__input_icon',
          placeholder: '~',
          disabled: true,
          key: 'icon'
        },
        {
          onChange: this.handleEndNumber,
          className: 'number-range-group__input',
          key: 'endNumber',
        }
      ]
    };
  }

  handleStartNumber = (e) => {
    let { onChange, value } = this.props;
    !value && (value = []);
    value[0] = e;
    if (!value[0] && !value[1]) {
      value = [];
    }
    onChange(value);
  };

  handleEndNumber = (e) => {
    let { onChange, value } = this.props;
    !value && (value = []);
    value[1] = e;
    if (!value[0] && !value[1]) {
      value = [];
    }
    onChange(value);
  };


  renderRange = (value = []) => {
    const { elementProps } = this.state;
    if (value === null) {
      value = [];
    }
    elementProps
      .map(item => {
        item.precision = 2;
        if (item.key === 'startNumber') {
          item.value = value[0];
          return item;
        }
        if (item.key === 'endNumber') {
          item.min  = value[0];
          item.value = value[1];
        }
        return item;
      });
    return elementProps.map(item => React.createElement(InputNumber, item));
  };


  render() {
    const { value } = this.props;
    return (
      <section className="number-range">
        <InputGroup compact size="large" className="number-range-group">
          {this.renderRange(value)}
        </InputGroup>
      </section>
    );
  }
}

NumberRange.propTypes = {
  value: React.PropTypes.any,
  onChange: React.PropTypes.func
};

export default NumberRange;
